//全局语言对象
var oss = "http://foodievc.oss-ap-southeast-1.aliyuncs.com/", //国外
	oss2 = "http://foodietest.oss-cn-beijing.aliyuncs.com/", //国内
	isAPP = navigator.userAgent.match(/Html5Plus/i),
	android_bak = true, //设置安卓返回键；
	root_a = "http://api-test.foodie.vc/",
	jum_root="http://u-test.foodie.vc/WEB_APP/web_client/",//页面跳转配置
	jsonpath = "http://api-test.foodie.vc/interface.php?ver=10&mo=u&a=",
	jsonpathY = "http://api-test.foodie.vc/yhohuat.php?ver=1&mo=u&a=",
	tab_and_fod = "http://foodietest.oss-cn-beijing.aliyuncs.com/", //测试使用
	//var tab_and_fod = "http://foodievc.oss-ap-southeast-1.aliyuncs.com/" //正式使用
	global_whatsapp = "https://api.whatsapp.com/send?phone=60177740986",
	api_root = root_a + "interface.php?ver=10&mo=u2&a=",
	api_img = root_a + "interface.php?ver=10&mo=u2&a=upload_Img",
	is_ajax_send = "0", //锁定ajax
	isAPP = navigator.userAgent.match(/Html5Plus/i), //判断是否为app
	root = "123", //版本号
	lg = "", //语言
	support = true, //刷新按钮开关
	defaultAvatar = "../image/default.jpg", //默认头像
	con_img = "http://foodievc.oss-ap-southeast-1.aliyuncs.com/app/ClientApp/image/default2.png", //默认图片
	con_bg_img = "http://foodievc.oss-ap-southeast-1.aliyuncs.com/app/ClientApp/image/index/5_03.png", //默认背景图
	phone_lg = "", //手机默认语言
	phone_uuid = null, //手机唯一标识
	gpush_clientid = null, //手机唯一标识
	gpush_token = null, //手机唯一标识
	hour, minute, second, //时 分 秒
	timestamp_pe = null, //App从前台切换至后台所经过的时间
	timestamp_bg = null, //App从后台切换至前台所经过的时间
	set_p = {}, //可拖拽长度
    wss1 = null,//存储加载中的弹框
	uss = navigator.userAgent,
	_BARCODE = '', //插件别名
	_B = '', //插件方法
	plugin_fun = {}, //调用壳里面的方法
	//var newsaudio = new Audio(); //提示音乐
	//newsaudio.src = "../audio/ts.mp3";
	isAndroid = uss.indexOf('Android') > -1 || uss.indexOf('Adr') > -1, //android终端
	global_lange_config = {
		"zh": {
			name: "简体中文",
			val: "zh"
		},
		"en": {
			name: "English",
			val: "en"
		},
		"ms": {
			name: "Melayu",
			val: "ms"
		}
	};
//取消浏览器的所有事件，使得active的样式在手机上正常生效
document.addEventListener('touchstart', function() {
	return false;
}, true);
// 禁止选择
document.oncontextmenu = function() {
	return false
};
//页面跳转
function jum(h) {
	clicked(h);
}
//全局返回上一页
function com_back() {
	back()
}
//Android返回
function And_back(page, a) {
	mui.back = function() {}
	if(navigator.userAgent.match(/Html5Plus/i)) {
		plus.key.removeEventListener("backbutton", plus_back1);
		plus.key.removeEventListener("backbutton", plus_back2);
		plus.key.removeEventListener("backbutton", plus_back3);
		plus.key.removeEventListener("backbutton", plus_back4);
		plus.key.removeEventListener("backbutton", plus_back6);
		if(page == "tab_sta") {
			plus.key.addEventListener("backbutton", plus_back2, false);

		} else if(page == "remove") {
			plus.key.addEventListener("backbutton", plus_back2, false);
		} else if(page == "index") {
			plus.key.addEventListener("backbutton", plus_back3, false);

		} else if(page == "con_order") {
			plus.key.addEventListener("backbutton", plus_back4, false);
		} else if(page == "myShop2") {
			plus.key.addEventListener("backbutton", plus_back6, false);
		} else if(page == "no") {
			plus.key.addEventListener("backbutton", function() {}, false);
		}
	}

}

function plus_back1() {
	var ws = plus.webview.currentWebview()
	plus.webview.close(ws.id)
}

function plus_back2() {
	back();
}
var backButtonPress2 = 0

function plus_back3() {
	if(backButtonPress2 >= 1) {
		plus.runtime.quit();
	} else {
		plus.nativeUI.toast(JSON.parse(getItem("Langues"))['1349']);
	}
	backButtonPress2++;
	setTimeout(function() {
		backButtonPress2 = 0;
	}, 1000);
	return false;
}

function plus_back4() {
	var ws = plus.webview.currentWebview()
	var ms = plus.webview.currentWebview().opener()
	//	var preUrl = plus.webview.getWebviewById(getItem("tableStatus.html"));
	ms.evalJS('refresh()')
	plus.webview.close(ws.id)
}

function plus_back6(a) {
	var ws = plus.webview.currentWebview()
	var preUrl = plus.webview.currentWebview().opener();
	preUrl.evalJS('refresh()');
	preUrl.evalJS('bank_btn(2)');
	plus.webview.close(ws.id)
}

function Refresh_bth() { //刷新按钮
	//	var ss =  window.location.href;
	//	window.location.href = ss+ Math.random()
	history.go(0)
}

function Refresh_str() {
	var str = " <div style='position: fixed; top: 0; z-index: 9999999999999; font-size:30px' onclick='Refresh_bth()'>刷新</div>"
	$("#app").append(str);
}
var myDate = "";
//下拉刷新	
function down_load() {
	if(isAPP) {
		var ws = plus.webview.currentWebview();
		set_p = {
			support: true,
			style: 'circle', //必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
			color: '#fd5749', //可选，默认“#2BD009” 下拉刷新控件颜色
			height: '50px', //可选,默认50px.下拉刷新控件的高度,
			range: '100px', //可选 默认100px,控件可下拉拖拽的范围
			offset: '-10px', //可选 默认0px,下拉刷新控件的起始位置
			auto: false, //可选,默认false.首次加载自动上拉刷新一次
			contentdown: {
				caption: "下拉可以刷新"
			},
			contentover: {
				caption: "释放立即刷新"
			},
			contentrefresh: {
				caption: "正在刷新..."
			}

		}
		ws.setPullToRefresh(set_p, function() {
			try {
				refresh(); //全局刷新
			} catch(e) {

			}
			//				back_index(1) //刷新方法
			ws.endPullToRefresh();
		});
	}

}
$(function() {
	function plusReady1() {
		var a = getItem("lg"); //读取本语言缓存
		//ISO去除延迟
		//加载本地语言包
		lang(a, function(h) {
			FastClick.attach(document.body);
			global_lange = h;
			if(isAPP) {
				plugintest = {
					// 声明异步返回方法
					PluginTestFunction: function(Argus1, successCallback, errorCallback, name) { //arry:传递的参数[插件别名,方法名]
						var success = typeof successCallback !== 'function' ? null : function(args) {
								successCallback(args);
							},
							fail = typeof errorCallback !== 'function' ? null : function(code) {
								errorCallback(code);
							};
						callbackID = _B.callbackId(success, fail);
						// 通知Native层plugintest扩展插件运行”PluginTestFunction”方法
						//							return B.exec(_BARCODE, "PluginTestFunction", [callbackID,Argus1]);
						//							return B.exec(_BARCODE, "PluginLoginFacebook", [callbackID,Argus1]);
						return _B.exec(_BARCODE, name, [callbackID, Argus1]);
					},
					PluginTestFunctionSync: function(Argus1, Argus2) {
						// 通知Native层plugintest扩展插件运行“PluginTestFunctionSync”方法并同步返回结果         
						alert(_B.execSync(_BARCODE, "PluginTestFunctionSync", [Argus1, Argus2]))
						//							return B.execSync(_BARCODE, "PluginTestFunctionSync", [Argus1, Argus2]);
					}
				}
				window.plus.plugintest = plugintest;
			}
			setTimeout(function(){
				fun1();
			},300)
			//			Refresh_str(); //测试使用的刷新方法
		});
	
	
	}
	if(isAPP) {
		document.addEventListener('plusready', plusReady1, false);
	}else{
		plusReady1();
	}
	//判断是否app
})

//退出清除缓存
function global_signout(a) {
	removeItem("logStar"); //登录状态
	removeItem("yingsoft_home_encode");
	removeItem("yingsoft_home_member_id");
	removeItem("yingsoft_home_member_username");
	removeItem("yingsoft_home_member_nickname");
	removeItem("yingsoft_home_member_headimgurl");
	clearInterval(timejson);
		if(wss1 != null) {
			wss1.close();
		}
	clicked('../login/login.html')

}
//ajax加载语言包
function lang(v, call, type) {
	if(!v) {
		var lg = navigator.language.toLowerCase().substr(0, 2)
		var langarr = ["zh", "en", "ms"]
		if(langarr.indexOf(lg) == -1) lg = "en"
		setItem("lg", lg);
		v = lg;
	}
	var l = getItem("Langues"); //json
	var lang = getItem("lg"); //zh en ms
	lg = lang;
	if(l && v == lang && !type) { //vue回调
		call(JSON.parse(l));
	} else { //切换与初始化语言
		$.ajax({
			type: "get",
			dataType: "json",
			// url: "language/" + 'zh' + ".json?" + Math.random(),
			url: "api",
			success: function(h) {
				setItem("Langues", JSON.stringify(h));
				setItem("lg", v);
				call(h);
			},
			error: function(e) {
				console.log("语言包加载错误");
				debugger
			}
		});
	}
}

//缓存json数据
function global_json1(url, call) {
	var ss = JSON.parse(getItem("my_msg"));
	var aa = "";
	aa = tab_and_fod + url + ss.shop_id + "_" + getItem("lg") + ".json?"+Math.random();
	$.ajax({
		type: "get",
		dataType: "json",
		url: aa,
		success: function(h) {
			call(h)
		},
		error: function() {
			alert("接口错误", "提示");
		}
	});
}
//统计点击次数
function click_ajax(data, call) {
	$.ajax({
		"type": "post",
		"dataType": "String",
		"data": data,
		headers: {
			"WAITER-ENCODE": getItem("yingsoft_home_encode")
		},
		"url": "http://api-test.foodie.vc/index.php?s=/Home/Adv/put_click",
		"success": function(h) {
			call(h);
		},
		"error": function(e) {}
	})

}
//登录前ajax
function common_ajax_log(type, data, href, call) { //type:1获取数据 2:获取json文件 请求memberid 与shopid  data:传入数据      call:成功回调  href:接口名称 4:获取图片
	if(isAPP) {
		plus.push.getClientInfo();
		data.uuid = plus.device.uuid;
	} else {
		data.uuid = "866982030752101,866982030752119"; //pc虚拟一个uuid方便测试
	}
	if(is_ajax_send == "1") { //判断ajax是否处于锁定状态 0:未锁定 1:已锁定
		console.log("重复调用接口")
		return;
	}
	is_ajax_send = "1";
	var url, headers = {};
	timejson = setInterval(function() {
		clearInterval(timejson);
		if(isAPP) {
			wss1 = plus.nativeUI.showWaiting("loading...", {
				loading: {
					display: "inline"
				}
			});
		}
	}, 700);
	lg = getItem("lg");
	if(type == 1) { //登录注册忘记密码
		url = api_root + href + '&l=' + lg;
	}
	if(type == 1) {
		$.ajax({
			"type": "post",
			"dataType": "json",
			"data": data,
			"url": url,
			"success": function(h) {
				//if(h.status==2 || h.status==3 && type==2){1成功 0失败 2登录超时 3帐号锁定
				success(h);

			},
			"error": function(e) {
				console.log(JSON.stringify(e))
				errors(e);
			}
		})
	}
	//ajax成功后回调
	function success(h) {
		is_ajax_send = 0;
		clearInterval(timejson);
		if(wss1 != null) {
			wss1.close();
		}
		//判断是否登录异常
		if(h.status == 2 || h.status == 3) { //1成功 0失败 2登录超时 3帐号锁定
			global_signout(h.msg); //全局退出
		} else {
			//判断接口版本如果发生改变执行重启
				var v = getItem("ajax_ver"); //存储接口版本
				var ver = h.ver; //当前请求的接口版本
				if(v == null || v == ver) { //null说明是第一次使用 
					setItem("ajax_ver", ver); //缓存当前接口的版本号
					call(h);
				} else {
					setItem("ajax_ver",ver); //缓存当前接口的版本号
					if(isAPP) {
						mui.alert(global_lange["1386"], global_lange["1023"], global_lange["1139"], function() {
							plus.runtime.restart(); //重启APP
						}, "div")
					}
				}
		}

	}

	//ajax错误回调
	function errors(e) {
		is_ajax_send = 0;
		if(wss1 != null) {
			wss1.close();
		}
		mui.alert("Network anomaly", global_lange["1023"], global_lange["1025"], function() {
			plus.runtime.restart(); //重启APP
		}, "div")
//		clearInterval(timejson);
	}
}
//请求数据ajax
function common_ajax(type, data, href, call) { //type:1获取数据 2:获取json文件 请求memberid 与shopid  data:传入数据      call:成功回调  href:接口名称 4:获取图片
	data.uuid = getItem("uuid")
	if(is_ajax_send == "1") { //判断ajax是否处于锁定状态 0:未锁定 1:已锁定
		console.log("重复调用接口")
		return;
	}
	var head = {
		"MEMBER-ENCODE": getItem("yingsoft_home_encode")
	}
	var wss1 = null;
	is_ajax_send = "1";
	var url, headers = {};
	timejson = setInterval(function() {
		clearInterval(timejson);
		if(isAPP) {
			wss1 = plus.nativeUI.showWaiting("loading...", {
				loading: {
					display: "inline"
				}
			});
		}
	}, 700);
	lg = getItem("lg");
	if(type == 1) { //登录注册忘记密码
		url = api_root + href + '&l=' + lg;
	}
	if(type == 1) {
		$.ajax({
			"type": "post",
			"dataType": "json",
			//			"timeout": 20000,
			"data": data,
			headers: head,
			"url": url,
			"success": function(h) {
				if(h.status == 2 || h.status == 3 && type == 2) { //1成功 0失败 2登录超时 3帐号锁定
					global_signout(h.msg); //全局退出
				} else {
					success(h);
				}
				
			},
			"error": function(e) {
				errors(e);
			}
		})
	}
	if(type == 2) {
		$.ajax({
			"type": "get",
			"dataType": "json",
			"timeout": 20000,
			"data": data,
			"url": 'http://foodietest.oss-cn-beijing.aliyuncs.com//shop_goods/8_zh.json',
			"success": function(h) {
				success(h);
			},
			"error": function(e) {
				errors(e);
			}
		})
	}
	if(type == 4) {
		//上传图片用
		$.ajax({
			type: "post",
			dataType: "json",
			timeout: 15000,
			url: api_img,
			headers: {
				"MEMBER-ENCODE,SHOP-ENCODE": getItem("yingsoft_home_encode")
			},
			data: data,
			contentType: false,
			processData: false,
			success: function(h) {
				success(h);
			},
			error: function(e) {
				mui.alert(JSON.stringify(e), app.lang[1023], app.lang[1139], function() {}, "div")
				success(0);
			}
		});
	}
	//ajax成功后回调
	function success(h) {
		is_ajax_send = 0;
		clearInterval(timejson);
		if(wss1 != null) {
			wss1.close();
		}
		//判断是否登录异常
		if(h.status == 2 || h.status == 3) { //1成功 0失败 2登录超时 3帐号锁定
			global_signout(h.msg); //全局退出
		} else {
			//判断接口版本如果发生改变执行重启
			var v = getItem("ajax_ver"); //存储接口版本
			var ver = h.ver; //当前请求的接口版本
			if(v == null || v == ver) { //null说明是第一次使用  相等不需要重启
				setItem("ajax_ver", ver); //缓存当前接口的版本号
				call(h);
			} else {
				setItem("ajax_ver", ver); //缓存当前接口的版本号
				if(isAPP) {
					mui.alert(global_lange["1386"], global_lange["1023"], global_lange["1025"], function() {
						plus.runtime.restart(); //重启APP
					}, "div")
				}

			}
		}

	}

	//ajax错误回调
	function errors(e) {
		
		is_ajax_send = 0;
		if(wss1 != null) {
			wss1.close();
		}
		mui.alert("Network anomaly", global_lange["1023"], global_lange["1025"], function() {
			plus.runtime.restart(); //重启APP
		}, "div")
		
		
	}
}
//验证是否有权限

function verify(num, call) {
	var str = "<div id='table_open_mask' class='mask' style='z-index: 99;'></div><div id='verification' class='jurisdiction fiex'><div class='jurisdiction_son fiex1'><div class='fiex f-20 center mag-b-20'>" + global_lange["1496"] + "</div><div class='fiex mag-b-20'><div class='f-18 mag-r-10'>" + global_lange["1497"] + "</div><div class='fiex1'><input id='account' placeholder=" + global_lange['1152'] + " type='tel' /></div></div><div class='fiex mag-b-20'><div class='f-18 mag-r-10'>" + global_lange["1498"] + "</div><div class='fiex1'><input id='password' placeholder=" + global_lange['1004'] + " type='password' /></div></div><div class='fiex'><div class='fiex1 center'><div id='verification_sub' class='btn btn_c'>" + global_lange["1190"] + "</div></div><div class='fiex1 center'><div id='verification_cancle' style='background: #aaa;' class='btn btn_c'>" + global_lange["1049"] + "</div></div></div></div></div>"

	function dele_str() {
		$("#table_open_mask").remove()
		$("#verification").remove()
	}
	var m = JSON.parse(getItem("shop_table_cookbook")).rule_list;
	if(m == null) {
		call(1)
		return
	}
	var account = "";
	var password = "";
	var s = false
	$.each(m, function(k, v) {
		if(num == v) {
			s = true
			return false
		}
	});
	if(s) {
		popups();

	} else {
		call(1)
	}
	//验证弹出层
	function popups() {
		$("#app").append(str)
		document.getElementById("table_open_mask").addEventListener('touchmove', function(e) {
			e.preventDefault()
		}, false)
		document.getElementById("verification").addEventListener('touchmove', function(e) {
			e.preventDefault()
		}, false)

		$('#verification_sub').unbind("click");
		$('#verification_cancle').unbind("click");
		$("#verification_sub").on("click", function() {
			var a = $("#account").val()
			var p = $("#password").val()
			setajx(a, p)
		})
		$("#verification_cancle").on("click", function() {
			dele_str()
		})
	}

	function setajx(a, p) {
		common_ajax("1", {
			"username": a,
			"password": p,
			"rule_id": num
		}, "get_cashier_validation", function(e) {
			var star = e.status;
			if(star == 1) {
				$("#table_open_mask").addClass('hide')
				$("#verification").addClass('hide')
				call(1);
				dele_str();
			} else {
				call(0);
			}
		})
	}
}